import { useReactive } from "ahooks";
import { useModel } from "umi";
import { useEffect } from "react";
import compress from "gql-compress";

const useAllInstitutions = (oiType) => {
    const { graphqlFetch } = useModel("global");

    const state = useReactive({
        loading: false,
        institutions: [],
    });

    const loadAllInstitutions = async () => {
        state.loading = true;
        let res = await graphqlFetch({
            query,
            variables: {
                oiType,
            },
        });
        state.institutions = res?.a?.nodes || [];
        state.loading = false;
        return res?.a?.nodes || [];
    };

    useEffect(() => {
        oiType && loadAllInstitutions(oiType);
    }, [oiType]);

    return { ...state, loadAllInstitutions };
};

const query = compress(`query MyQuery($oiType: String!) {
    a: allOrganizationInstitutions(condition: {oiType: $oiType, oiRoot: null}, orderBy: PY_NAME_ASC) {
        nodes {
            asInfo
            crInfo
            maInfo
            mpInfo
            oiCity
            oiComm
            oiDesc
            oiDist
            oiEsta
            oiLeve
            oiName
            oiPaid
            oiPhon
            oiPrin
            oiRoot
            oiStat
            oiStre
            oiType
            oiUuid
            oiZoja
            otInfo
            ptInfo
            pyName
            upInfo
            oiAddr
            ptInfo
        }
    }
}`);

export default useAllInstitutions;
